package com.bkhech.boot.sample.mvc.permission;

import com.bkhech.boot.configure.security.core.api.permission.PermissionApi;
import com.bkhech.boot.sample.mvc.contants.SecurityCons;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 权限 API {@link PermissionApi} 默认实现类
 * @author guowm
 * @date 2023/2/2
 */
@Service
public class DefaultPermissionApiImpl implements PermissionApi {
    Map<Long, List<String>> permissionMap = Map.ofEntries(
      Map.entry(1L, List.of("system:user:get", "system:user:put")),
      Map.entry(2L, List.of("system:user:get"))
    );
    Map<Long, List<String>> roleMap = Map.ofEntries(
      Map.entry(1L, List.of(SecurityCons.roleAdminCode)),
      Map.entry(2L, List.of(SecurityCons.roleCommonUserCode))
    );
    @Override
    public boolean hasAnyPermissions(Long userId, String... permissions) {
        // 没设置权限，默认无权限
        if (Objects.isNull(permissions) || permissions.length == 0) {
            return false;
        }
        if (!permissionMap.containsKey(userId)) {
            return false;
        }
        return Arrays.stream(permissions).anyMatch(permissionMap.get(userId)::contains);
    }

    @Override
    public boolean hasAnyRoles(Long userId, String... roles) {
        // 没设置角色，默认无角色
        if (Objects.isNull(roles) || roles.length == 0) {
            return false;
        }
        if (!permissionMap.containsKey(userId)) {
            return false;
        }
        return Arrays.stream(roles).anyMatch(roleMap.get(userId)::contains);
    }
}
